//
//  Plugin_VipCustomer.m
//  SuperSDK_Plugin_VipCustomer
//
//  Created by 涂俊 on 2019/4/18.
//  Copyright © 2019 wyht. All rights reserved.
//

#import "Plugin_VipCustomer.h"
#import <AdSupport/AdSupport.h>

#import "VipCustomerManager.h"
#import "ArgumentStore.h"

#import "YCSuperSDK/SSDKEventKeys.h"
#import "YCSuperSDK/SSDKEventManager.h"
#import "YCSuperSDK/SSDKDataKeys.h"
#import "YCSuperSDK/SuperSDKInst.h"

#import "SuperSDKPluginTools/SSDKPluginUIUtil.h"
#import "SuperSDKPluginTools/SSDKPluginJsonUtil.h"

NSString *const PVIPAppId = @"appId";
NSString *const PVIPPubKey = @"pubKey";
NSString *const PVIPUid = @"uid";

@interface Plugin_VipCustomer() <VipCustomerDelegate>

@property(nonatomic, strong)UIView *indicatorContainerView;
// 小菊花
@property(nonatomic, strong)UIActivityIndicatorView *activityIndicator;
@end

@implementation Plugin_VipCustomer

{
    NSString *callBackObj;
    NSString *callBackFun;
    NSDictionary *vipConfig;
    
    NSString *gameRoleId;
    NSMutableDictionary *loginRecord;
}

-(void) initInfo {
    loginRecord = [[NSMutableDictionary alloc] init];
    [SSDKEventManager addObsver:self selector:@selector(applicationDidFinishLaunchingEvent:) name:EVENT_APPLICATION_DIDFINISHLAUNCHINGWITHOPTIONS object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(enterGame:) name:EVENT_SUBMITDATA object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(gameInit:) name:@"VipCustomerService_init" object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(open:) name:@"VipCustomerService_open" object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(openKeFu:) name:@"VipCustomerService_openKeFu" object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(unreadMsg:) name:@"VipCustomerService_unreadMsg" object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(opLogin:) name:@"VipCustomerService_openLogin" object:nil className:@"Plugin_VipCustomer"];
    [SSDKEventManager addObsver:self selector:@selector(gameLoginAgain:) name:@"VipCustomerService_gameLoginAgain" object:nil className:@"Plugin_VipCustomer"];
}

-(void) applicationDidFinishLaunchingEvent:(NSNotification*) notification {
    NSLog(@"Plugin_VipCustomer applicationDidFinishLaunchingEvent!");
    NSDictionary *launchOptions = [[notification object] objectForKey:SSDK_E_DIDFINISHLAUNCHWITHOPTIONS];
    NSDictionary *config = [[[NSBundle mainBundle] infoDictionary] objectForKey:SSDK_L_CONFIG];
    if (config != nil) {
         vipConfig = [config objectForKey:@"PLUGIN_Config_VipCustomer"];
        if (vipConfig != nil) {
            NSString *imAppKey = [vipConfig objectForKey:@"imAppKey"];
            NSString *imTenantId = [vipConfig objectForKey:@"imTenantId"];
            NSString *imConversationId = [vipConfig objectForKey:@"imConversationId"];
            BOOL log = [[vipConfig valueForKey:@"log"] boolValue];
            // 初始化
            [[VipCustomerManager getInstance] init:launchOptions
                                            params:@{@"url":@"http://customer.sail2world.com/vipcustomer/api",
//             params:@{@"url":@"http://testssdk.sail2world.com/vipcustomer/api",
                                                     @"imAppKey":imAppKey,
                                                     @"imTenantId":imTenantId,
                                                     @"imConversationId":imConversationId}
                                               log:log];
            // 添加监听回调
            [[VipCustomerManager getInstance] setDelegate:self];
            [self opLogin:nil];
            return;
        }
    }
    NSLog(@"Plugin_VipCustomer init fail! missing params, params=%@", config);
}

// 游戏调用初始化接口
-(void) gameInit:(NSNotification*) notification {
    NSDictionary *args = [SSDKPluginJsonUtil toObjectWithJson:[notification object]];
    callBackObj=[args objectForKey:@"UNITY_OBJ"];
    callBackFun=[args objectForKey:@"UNITY_PLUGIN_CALLBACK"];
}

//进入游戏时，调用login接口
-(void) enterGame:(NSNotification*) notification {
    if([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LOGIN_EVENT]) {
        NSDictionary *object = [notification object];
        NSString *roleId = [object objectForKey:SUBMIT_ROLE_ID];
        [self gameLoginWithRoleId:roleId result:nil];
    } else if ([[[notification object] objectForKey:SUBMIT_EXT] isEqualToString:SUBMIT_LOGOUT_EVENT]) {
        [self ucLoginWithResult:nil];
    }
}

- (void)gameLoginAgain:(NSNotification *)notification {
    if (!gameRoleId) { return; }
    [self gameLoginWithRoleId:gameRoleId result:nil];
}

// 游戏登录
- (void)gameLogin:(NSNotification *)notification {
    NSDictionary *object = [SSDKPluginJsonUtil toObjectWithJson:[notification object]];
    NSString *roleId = [object objectForKey:SUBMIT_ROLE_ID];
    [self gameLoginWithRoleId:roleId result:nil];
}

// open sdk 登录
- (void)opLogin:(NSNotification *)notification {
    [self ucLoginWithResult:nil];
}

// 打开客服界面
-(void) open:(NSNotification*) notification {
    
    if (gameRoleId == nil) {
        [[VipCustomerManager getInstance] alert:@"请先登录"];
        return;
    }
    
    // 将 appId 和 pubKey 在一步获取
    NSDictionary *args = [SSDKPluginJsonUtil toObjectWithJson:[notification object]];
    
    // 小菊花 开始
    [self activityIndicatorStartAnimating];
    
    __weak typeof(self) weakSelf = self;
    [self gameLoginWithRoleId:gameRoleId result:^(BOOL rst) {
        // 小菊花 结束
        [weakSelf activityIndicatorStopAnimating];
        if (rst) {
            [weakSelf openWithArgs:args];
        } else {
            [[VipCustomerManager getInstance] alert:@"登录客服失败，请稍后再试"];
        }
    }];
}

- (void)openKeFu:(NSNotification*) notification {
    // 将 appId 和 pubKey 在一步获取
    NSDictionary *args = [SSDKPluginJsonUtil toObjectWithJson:[notification object]];
    
    // 小菊花 开始
    [self activityIndicatorStartAnimating];
    
    __weak typeof(self) weakSelf = self;
    [self ucLoginWithResult:^(BOOL rst) {
        // 小菊花 结束
        [weakSelf activityIndicatorStopAnimating];
        if (rst) {
            [weakSelf openKeFuWithArgs:args];
        } else {
            [[VipCustomerManager getInstance] alert:@"登录客服失败，请稍后再试"];
        }
    }];
}

- (void)gameLoginWithRoleId:(NSString *)roleId result:(void (^)(BOOL rst))resultBlock {
    NSString *appId = [vipConfig objectForKey:@"appId"];
    NSString *pubKey = [vipConfig objectForKey:@"pubKey"];
    if (!appId || !pubKey || !roleId) {
        return;
    }
    
    NSString *uid = [self uid];
    gameRoleId = roleId;
    [self loginWithAppId:appId pubKey:pubKey uid:uid roleId:roleId result:resultBlock];
}

- (void)ucLoginWithResult:(void (^)(BOOL rst))resultBlock {
    // 兼容之前的逻辑
    NSString *appId = [vipConfig objectForKey:@"opAppId"];
    NSString *pubKey = [vipConfig objectForKey:@"opPubKey"];
    
    if (!appId || !pubKey) {
        return;
    }
    NSString *uid = [self uid];
    NSString *roleId = [self deviceId];
    [self loginWithAppId:appId pubKey:pubKey uid:uid roleId:roleId result:resultBlock];
}

- (void)loginWithAppId:(NSString *)appId pubKey:(NSString *)pubKey uid:(NSString *)uid roleId:(NSString *)roleId result:(void (^)(BOOL rst))resultBlock {
    [[VipCustomerManager getInstance] loginWithAppId:appId pubKey:pubKey uid:uid roleId:roleId result:^(BOOL result) {
        if (resultBlock) {
            resultBlock(result);
        }
    }];
}

// 打开游戏客服
- (void)openWithArgs:(NSDictionary *)args {
    NSString *uid = [self uid];// 不需要游戏传入，通过supersdk获取
    NSString *roleId=[args objectForKey:@"role_id"];
    NSString *roleName=[args objectForKey:@"role_name"];
    NSString *serverName=[args objectForKey:@"server_name"];
    NSString *os=[args objectForKey:@"os"];
    NSString *network=[args objectForKey:@"network"];
    NSString *rom=[args objectForKey:@"rom"];
    NSString *ram=[args objectForKey:@"ram"];
    
    NSDictionary *data = [[NSBundle mainBundle] infoDictionary];
    NSString *gameName = [data objectForKey:@"CFBundleDisplayName"];
    NSString *gameVersion = [data objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *config = [data objectForKey:SSDK_L_CONFIG];
    NSString *sdkName = @"";
    NSString *channelId = @"";
    if (config!=nil) {
        sdkName = [config objectForKey:@"SDK_CLASS"];
        channelId = [config objectForKey:@"SSDK_CHANNEL_ID"];
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *rootViewController = [self currentViewController];
        [[VipCustomerManager getInstance] open:@{
                                                 @"uid":uid,
                                                 @"roleId":roleId,
                                                 @"roleName":roleName,
                                                 @"serverName":serverName,
                                                 @"gameName":gameName,
                                                 @"gameVersion":gameVersion,
                                                 @"sdkId":sdkName,
                                                 @"channelId":channelId,
                                                 @"os":os,
                                                 @"network":network,
                                                 @"rom":rom,
                                                 @"ram":ram}
                                    controller:rootViewController];
    });
}

//
- (void)openKeFuWithArgs:(NSDictionary *)args {
//    NSDictionary *args = [SSDKPluginJsonUtil toObjectWithJson:[notification object]];
    NSString *uid = [self uid];// 不需要游戏传入，通过supersdk获取
    NSString *roleId=[args objectForKey:@"role_id"];
    NSString *roleName=[args objectForKey:@"role_name"];
    NSString *serverName=[args objectForKey:@"server_name"];
    NSString *os=[args objectForKey:@"os"];
    NSString *network=[args objectForKey:@"network"];
    NSString *rom=[args objectForKey:@"rom"];
    NSString *ram=[args objectForKey:@"ram"];
    
    NSDictionary *data = [[NSBundle mainBundle] infoDictionary];
    NSString *gameName = [data objectForKey:@"CFBundleDisplayName"];
    NSString *gameVersion = [data objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *config = [data objectForKey:SSDK_L_CONFIG];
    NSString *sdkName = @"";
    NSString *channelId = @"";
    if (config!=nil) {
        sdkName = [config objectForKey:@"SDK_CLASS"];
        channelId = [config objectForKey:@"SSDK_CHANNEL_ID"];
    }
    if (roleId == nil || roleId.length == 0) {
        roleId = [self deviceId];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        UIViewController *rootViewController = [self currentViewController];
        [[VipCustomerManager getInstance] open:@{
            @"uid":uid,
            @"roleId":roleId,
            @"roleName":roleName,
            @"serverName":serverName,
            @"gameName":gameName,
            @"gameVersion":gameVersion,
            @"sdkId":sdkName,
            @"channelId":channelId,
            @"os":os,
            @"network":network,
            @"rom":rom,
            @"ram":ram}
                                    controller:rootViewController];
    });
}

// 游戏调用未读消息
-(void) unreadMsg:(NSNotification*) notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSNumber *num = [[VipCustomerManager getInstance] getUnReadMsgNum];
        if (self->callBackObj != nil && self->callBackFun != nil) {
            // 返回游戏，未读消息数量
            NSString *type = @"unreadMsg";
            if ([ArgumentStore.current.type isEqual: @"1"]) {
                type = @"opUnreadMsg";
            }
            NSString *dataStr = [SSDKPluginJsonUtil toJsonWithObject:@{@"type":type, @"value":[num stringValue] }];
            [SSDKEventManager postNotificationName:EVENT_PLUGIN_CALLBACK
                                            object:@{CALLBACK_E_OBJ: self->callBackObj,
                                                     CALLBACK_E_METHOD: self->callBackFun,
                                                     CALLBACK_E_MSG: dataStr}];
        }
    });
}

- (NSString *)uid {
    NSString *uid = [[SuperSDKInst getInstance] uid];
    if (uid && uid.length > 0) {
        return uid;
    }
    return [self deviceId];
}

- (NSString *)deviceId {
    NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    return idfa;
}

- (void)activityIndicatorStartAnimating {
    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.activityIndicator == nil) {
            [self setupActivityIndicator];
        }
        self.indicatorContainerView.hidden = NO;
        [self.activityIndicator startAnimating];
    });
}

- (void)activityIndicatorStopAnimating {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.indicatorContainerView.hidden = YES;
        [self.activityIndicator stopAnimating];
    });
}

- (void)setupActivityIndicator {
    UIView *currentView = [self currentViewController].view;
    if (currentView == nil) {
        return;
    }
    _indicatorContainerView = [[UIView alloc] initWithFrame: [UIScreen mainScreen].bounds];
    _indicatorContainerView.backgroundColor = UIColor.clearColor;
    _indicatorContainerView.hidden = YES;
    [currentView addSubview:_indicatorContainerView];
    
    _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityIndicator.frame = CGRectMake((CGRectGetWidth(_indicatorContainerView.frame)-50)/2, (CGRectGetHeight(_indicatorContainerView.frame)-50)/2, 50, 50);
    [_indicatorContainerView addSubview:_activityIndicator];
}

- (UIViewController *)currentViewController {
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    UIViewController *vc = keyWindow.rootViewController;
    while (vc.presentedViewController) {
        vc = vc.presentedViewController;

        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = [(UINavigationController *)vc visibleViewController];
        } else if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = [(UITabBarController *)vc selectedViewController];
        }
    }
    return vc;
}

#pragma mark - VipCustomerDelegate回调

// im登录成功
- (void)imLoginResult:(BOOL)result {
    // 如果登录成功，获取未读消息数量，回调游戏
    if (result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNumber *num = [[VipCustomerManager getInstance] getUnReadMsgNum];
            if (self->callBackObj != nil && self->callBackFun != nil) {
                NSString *type = @"unreadMsg";
                if ([ArgumentStore.current.type isEqual: @"1"]) {
                    type = @"opUnreadMsg";
                }
                NSString *dataStr = [SSDKPluginJsonUtil toJsonWithObject:@{@"type":type, @"value":[num stringValue]}];
                [SSDKEventManager postNotificationName:EVENT_PLUGIN_CALLBACK
                                                object:@{CALLBACK_E_OBJ: self->callBackObj,
                                                         CALLBACK_E_METHOD: self->callBackFun,
                                                         CALLBACK_E_MSG: dataStr}];
            }
        });
    }
}

// 接收到im消息
- (void)receiveImMessage:(NSArray *)aMessages {
    if (callBackObj != nil && callBackFun != nil) {
        // 返回游戏，客服有新消息
        NSString *dataStr = [SSDKPluginJsonUtil toJsonWithObject:@{@"type":@"newMsg", @"value":@"true"}];
        [SSDKEventManager postNotificationName:EVENT_PLUGIN_CALLBACK
                                        object:@{CALLBACK_E_OBJ: callBackObj,
                                                 CALLBACK_E_METHOD: callBackFun,
                                                 CALLBACK_E_MSG: dataStr}];
    }
}

// 接收到客服系统交互动作，回调游戏
- (void)receiveAction:(NSDictionary *)data {
    if (callBackObj != nil && callBackFun != nil) {
        // 返回游戏，客服有新消息
        NSString *dataStr = [SSDKPluginJsonUtil toJsonWithObject:data];
        [SSDKEventManager postNotificationName:EVENT_PLUGIN_CALLBACK
                                        object:@{CALLBACK_E_OBJ: callBackObj,
                                                 CALLBACK_E_METHOD: callBackFun,
                                                 CALLBACK_E_MSG: dataStr}];
    }
    [[VipCustomerManager getInstance] close];
}

@end
